import datetime

from django.contrib.auth.hashers import make_password, check_password
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from user.models import SysUser


# Create your views here.
# 注册用户信息视图类
class RegisterView(APIView):
    def post(self, request):
        """
        用户注册
        :param request:
        :return:
        """
        username = request.data.get('username')  # 获取用户名
        password = request.data.get('password')  # 获取密码
        email = request.data.get('email', '')  # 获取邮箱
        phonenumber = request.data.get('phonenumber', '')  # 获取手机号
        print(username, password, email, phonenumber)

        if not username or not password:
            return Response({
                'code': 400,
                'message': '⽤户名和密码不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)
        # 检查⽤户名是否已存在
        if SysUser.objects.filter(username=username).exists():
            return Response({
                'code': 400,
                'message': '⽤户名已存在'
            })

        # 写入数据到MySQL库
        try:
            user = SysUser.objects.create(
                username=username,  # 用户名
                password=make_password(password),  # 密码
                email=email,  # 邮箱
                phonenumber=phonenumber,  # 手机号
                status=0,  # 默认正常状态
                create_time=datetime.datetime.now(),  # 创建时间
                update_time=datetime.datetime.now()  # 更新时间
            )

        except Exception as e:
            return Response({
                'code': 500,
                'message': f'注册失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response({
            'code': 200,
            'message': '注册成功',
            'data': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            }
        })


class LoginView(APIView):
    def post(self, request):
        """
        用户注册
        :param request:
        :return:
        """
        # 1.获取登录用户和密码信息
        username = request.data.get('username')  # 获取用户名
        password = request.data.get('password')  # 获取密码
        print(username, password)
        # 2.判断登录信息是否完整
        if not username or not password:
            return Response({
                'code': 400,
                'message': '⽤户名和密码不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            # 3.通过用户名获取用户对象
            user = SysUser.objects.get(username=username)  # 根据⽤户名获取⽤户对象
            # 4.验证密码的是否正确
            if check_password(password, user.password):
                # 生成 token
                # 5.⽣成JWT令牌刷新令牌
                # RefreshToken.for_user(用户表信息)-- 刷新令牌
                refresh = RefreshToken.for_user(user)
                # 获取刷新令牌
                # refresh_token = str(refresh)
                # print("refresh:", refresh_token)
                # 获取访问令牌
                access_token = str(refresh.access_token)
                print("access_token:", access_token)
                return Response({
                    'code': 200,
                    'message': '登录成功',
                    'data': {
                        'token': access_token,
                        'user': {
                            'id': user.id,
                            'username': user.username,
                            'email': user.email,
                            'avatar': user.avatar,
                            'phonenumber': user.phonenumber
                        }
                    }
                })
            else:
                return Response({
                    'code': 400,
                    'message': '密码错误'
                })
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'用户名与密码不正确，登录失败'
            })
